<template>
  <a-card class="contract-management-card" title="合同管理">
    <template #extra>
      <a-space>
        <a-button size="small" @click="refreshData">
          <template #icon>
            <icon-refresh />
          </template>
          刷新
        </a-button>
        <a-button
          size="small"
          @click="showExistingTemplates"
          v-perm="['lindi:tradeApplicationTemplateContract:get']"
        >
          <template #icon>
            <icon-folder />
          </template>
          查看已有合同模板
        </a-button>
        <a-button
          size="small"
          @click="showContractTemplates"
          v-perm="['lindi:tradeApplicationTemplateContract:get']"
        >
          <template #icon>
            <icon-file />
          </template>
          选择模板生成合同
        </a-button>
        <a-button
          size="small"
          type="primary"
          @click="showAddModal"
          v-perm="['lindi:tradeApplicationContract:add']"
        >
          <template #icon>
            <icon-plus />
          </template>
          上传合同
        </a-button>
      </a-space>
    </template>

    <!-- 合同列表 -->
    <div class="contract-list">
      <div v-if="props.loading" class="loading-container">
        <a-spin size="large" />
      </div>

      <div v-else-if="contractList.length === 0" class="empty-container">
        <a-empty description="暂无合同文件" />
      </div>

      <div v-else class="contract-grid">
        <div
          v-for="contract in contractList"
          :key="contract.id"
          class="contract-item"
        >
          <a-card class="contract-card" hoverable>
            <div class="contract-header">
              <div class="contract-icon">
                <a-avatar :size="48" class="bg-blue-100" shape="square">
                  <icon-file-pdf class="text-blue-600" />
                </a-avatar>
              </div>
              <div class="contract-info">
                <div class="contract-title">
                  {{ contract.contractName || "合同文件" }}
                </div>
                <div class="contract-meta">
                  <span class="contract-type">{{
                    getContractTypeText(contract.contractType)
                  }}</span>
                  <!-- <a-tag :color="getStatusColor(contract.status)" size="small">
                    {{ getStatusText(contract.status) }}
                  </a-tag> -->
                </div>
              </div>
            </div>

            <div class="contract-details">
              <div class="detail-row">
                <span class="detail-label">合同编号：</span>
                <span class="detail-value">{{
                  contract.contractNumber || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">合同金额：</span>
                <span class="detail-value amount">{{
                  contract.contractAmount
                    ? `${contract.contractAmount}万元`
                    : "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">签订日期：</span>
                <span class="detail-value">{{
                  contract.effectiveDate || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">文件大小：</span>
                <span class="detail-value">{{
                  formatFileSize(contract.fileSize)
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">文件类型：</span>
                <span class="detail-value">{{
                  contract.fileType?.toUpperCase() || "-"
                }}</span>
              </div>
              <div v-if="contract.contractTemplate" class="detail-row">
                <span class="detail-label">合同模板：</span>
                <span class="detail-value">{{
                  contract.contractTemplate?.templateName || "-"
                }}</span>
              </div>
              <div v-if="contract.remark" class="detail-row">
                <span class="detail-label">备注：</span>
                <span class="detail-value">{{ contract.remark }}</span>
              </div>
            </div>

            <div class="contract-actions">
              <a-space>
                <a-button size="mini" @click="previewContract(contract)">
                  <template #icon>
                    <icon-eye />
                  </template>
                  预览
                </a-button>
                <a-button
                  size="mini"
                  type="primary"
                  @click="downloadContract(contract)"
                >
                  <template #icon>
                    <icon-download />
                  </template>
                  下载
                </a-button>
                <a-button
                  size="mini"
                  @click="editContract(contract)"
                  v-perm="['lindi:tradeApplicationContract:update']"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                  编辑
                </a-button>
                <a-button
                  size="mini"
                  status="danger"
                  @click="deleteContract(contract)"
                  v-perm="['lindi:tradeApplicationContract:delete']"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>
      </div>
    </div>

    <!-- 新增/编辑合同弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="700px"
      @cancel="handleModalCancel"
      @close="handleModalCancel"
    >
      <template #footer>
        <a-button @click="handleModalCancel">取消</a-button>
        <a-button type="primary" :loading="submitLoading" @click="handleSubmit"
          >确定</a-button
        >
      </template>
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item field="contractName" label="合同名称" required>
          <a-input
            v-model="formData.contractName"
            placeholder="请输入合同名称"
          />
        </a-form-item>

        <a-form-item field="contractNumber" label="合同编号" required>
          <a-input
            v-model="formData.contractNumber"
            placeholder="请输入合同编号"
          />
        </a-form-item>

        <a-form-item field="contractType" label="合同类型" required>
          <a-select
            v-model="formData.contractType"
            placeholder="请选择合同类型"
          >
            <a-option
              v-for="(d, index) in dicts[
                proxy.DICT.lindiTradeApplicationContractType
              ]"
              :key="index"
              :label="d.dictValue"
              :value="d.dictKey"
            />
          </a-select>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="contractAmount" label="合同金额(万元)">
              <a-input
                v-model="formData.contractAmount"
                placeholder="请输入合同金额"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="effectiveDate" label="签订日期" required>
              <a-date-picker
                v-model="formData.effectiveDate"
                style="width: 100%"
                placeholder="请选择签订日期"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item field="contractFile" label="合同文件">
          <div class="file-upload-container">
            <!-- 已有附件展示区域 -->
            <div
              v-if="existingFiles.length > 0"
              class="existing-files-container mb-4"
            >
              <div class="mb-2 flex items-center justify-between">
                <div class="text-gray-500">
                  <icon-info-circle class="mr-1" /> 已上传合同文件
                </div>
              </div>
              <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
                <a-list-item v-for="file in existingFiles" :key="file.fileId">
                  <a-card class="file-card" hoverable>
                    <div class="flex items-start">
                      <div class="file-icon mr-3">
                        <a-avatar :size="40" shape="square">
                          <icon-file-pdf v-if="file.fileType === 'pdf'" />
                          <icon-file-image
                            v-else-if="
                              ['jpg', 'png', 'jpeg'].includes(file.fileType)
                            "
                          />
                          <icon-file v-else />
                        </a-avatar>
                      </div>
                      <div class="flex-1 overflow-hidden">
                        <div class="font-medium truncate mb-1">
                          {{ file.fileName }}
                        </div>
                        <div class="text-gray-500 text-xs mb-1">
                          上传时间：{{ file.uploadTime || "未知" }}
                        </div>
                        <div class="mt-2">
                          <a-space>
                            <a-button
                              size="mini"
                              type="primary"
                              @click="downloadFile(file)"
                            >
                              <template #icon> </template>
                              下载
                            </a-button>
                            <a-button size="mini" @click="previewFile(file)">
                              <template #icon> </template>
                              预览
                            </a-button>
                            <a-button
                              size="mini"
                              status="danger"
                              @click="removeExistingFile(index)"
                            >
                              <template #icon> </template>
                              删除
                            </a-button>
                          </a-space>
                        </div>
                      </div>
                    </div>
                  </a-card>
                </a-list-item>
              </a-list>
            </div>

            <uploadFile
              ref="contractUploadFileRef"
              :file-source="fs"
              :limit="1"
              :multiple="false"
              accept=".pdf,.doc,.docx"
              list-type="text"
              source-type="proxy"
              @upload-success="handleUploadSuccess"
            />
          </div>
        </a-form-item>

        <a-form-item field="remark" label="备注">
          <a-textarea
            v-model="formData.remark"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入备注信息"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 模板信息弹窗 -->
    <a-modal
      v-model:visible="templateDetailVisible"
      title="合同模板详情"
      :width="600"
      :footer="false"
      unmount-on-close
    >
      <div v-if="selectedTemplateInfo" class="template-detail">
        <div class="template-header">
          <div class="template-icon">
            <icon-file-pdf :size="32" style="color: #f53f3f" />
          </div>
          <div class="template-basic-info">
            <div class="template-name">{{ selectedTemplateInfo.fileName }}</div>
            <div class="template-meta">
              <a-tag
                :color="getTemplateStatusColor(selectedTemplateInfo.status)"
                size="small"
              >
                {{ getTemplateStatusText(selectedTemplateInfo.status) }}
              </a-tag>
              <span class="text-gray-500">{{
                formatFileSize(selectedTemplateInfo.fileSize)
              }}</span>
              <span class="text-gray-500">{{
                selectedTemplateInfo.fileType?.toUpperCase()
              }}</span>
            </div>
          </div>
        </div>

        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="文件名称">
            {{ selectedTemplateInfo.fileName }}
          </a-descriptions-item>
          <a-descriptions-item label="文件大小">
            {{ formatFileSize(selectedTemplateInfo.fileSize) }}
          </a-descriptions-item>
          <a-descriptions-item label="文件类型">
            {{ selectedTemplateInfo.fileType?.toUpperCase() }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(selectedTemplateInfo.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="模板状态">
            <a-tag
              :color="getTemplateStatusColor(selectedTemplateInfo.status)"
              size="small"
            >
              {{ getTemplateStatusText(selectedTemplateInfo.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDateTime(selectedTemplateInfo.updateTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">
            {{ selectedTemplateInfo.remark || "无" }}
          </a-descriptions-item>
        </a-descriptions>

        <div class="template-actions">
          <a-space>
            <a-button
              type="primary"
              @click="previewTemplate(selectedTemplateInfo)"
            >
              预览
            </a-button>
            <a-button @click="downloadTemplate(selectedTemplateInfo)">
              下载
            </a-button>
          </a-space>
        </div>
      </div>
    </a-modal>

    <!-- 合同模板列表弹窗 -->
    <a-modal
      v-model:visible="templateListVisible"
      title="选择模板生成合同"
      width="800px"
      :footer="false"
    >
      <div v-if="contractTemplatesLoading" class="text-center py-8">
        <a-spin size="large" />
        <div class="mt-2 text-gray-500">加载中...</div>
      </div>

      <div v-else-if="contractTemplates.length === 0" class="text-center py-8">
        <div class="text-gray-500">暂无合同模板</div>
      </div>

      <div v-else>
        <!-- 模板选择器 -->
        <a-form-item label="选择模板" class="mb-4">
          <a-select
            v-model="selectedTemplateId"
            placeholder="请选择合同模板"
            size="large"
            :loading="contractTemplatesLoading"
            :key="`template-selector-${contractTemplates.length}`"
            @change="onTemplateChange"
          >
            <a-option
              v-for="template in contractTemplates"
              :key="template.contractTemplateId"
              :value="template.contractTemplateId"
            >
              {{ template.contractTemplateName }}
            </a-option>
          </a-select>
        </a-form-item>

        <!-- 合同类型选择器 -->
        <a-form-item label="合同类型" class="mb-4">
          <a-select
            v-model="selectedContractType"
            placeholder="请选择合同类型"
            size="large"
          >
            <a-option
              v-for="(d, index) in dicts[
                proxy.DICT.lindiTradeApplicationContractType
              ]"
              :key="index"
              :label="d.dictValue"
              :value="String(d.dictKey)"
            />
          </a-select>
        </a-form-item>

        <!-- 合同模板信息展示 -->
        <div v-if="selectedTemplate" class="template-info-section">
          <a-divider>模板信息</a-divider>
          <a-card class="template-info-card" :bordered="false">
            <div class="template-header">
              <div class="template-icon">
                <a-avatar :size="48" shape="square" class="bg-blue-100">
                  <icon-file-pdf class="text-blue-600" />
                </a-avatar>
              </div>
              <div class="template-basic-info">
                <div class="template-name">
                  {{ selectedTemplate.contractTemplateName }}
                </div>
                <div class="template-meta">
                  <a-tag color="blue" size="small">
                    {{
                      dicts[proxy.DICT.lindiContractTemplateType][
                        selectedTemplate.contractTemplateType
                      ]["dictValue"] || "标准模板"
                    }}
                  </a-tag>
                </div>
              </div>
            </div>

            <a-descriptions
              :column="2"
              size="small"
              class="template-descriptions"
            >
              <a-descriptions-item label="文件名称">
                {{ selectedTemplate.contractTemplateFile?.fileName || "-" }}
              </a-descriptions-item>
              <a-descriptions-item label="文件大小">
                {{
                  formatFileSize(
                    selectedTemplate.contractTemplateFile?.fileSize
                  )
                }}
              </a-descriptions-item>
              <a-descriptions-item label="文件类型">
                {{
                  selectedTemplate.contractTemplateFile?.fileType?.toUpperCase()
                }}
              </a-descriptions-item>
              <a-descriptions-item label="创建时间">
                {{
                  formatDateTime(
                    selectedTemplate.contractTemplateFile?.createTime
                  )
                }}
              </a-descriptions-item>
              <a-descriptions-item label="模板状态">
                <a-tag
                  :color="
                    dicts[proxy.DICT.commonNumberStatus][
                      selectedTemplate.status
                    ]['dictClass']
                  "
                  size="small"
                >
                  {{
                    dicts[proxy.DICT.commonNumberStatus][
                      selectedTemplate.status
                    ]["dictValue"]
                  }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="备注">
                {{ selectedTemplate.remark || "-" }}
              </a-descriptions-item>
            </a-descriptions>

            <div
              class="template-actions"
              v-if="selectedTemplate.contractTemplateFile"
            >
              <a-space>
                <a-button
                  size="small"
                  @click="previewTemplate(selectedTemplate)"
                >
                  <template #icon><icon-eye /></template>
                  预览模板
                </a-button>
                <a-button
                  size="small"
                  type="outline"
                  @click="downloadTemplate(selectedTemplate)"
                >
                  下载模板
                </a-button>
                <a-button
                  size="small"
                  status="danger"
                  @click="deleteTemplate(selectedTemplate)"
                >
                  <template #icon><icon-delete /></template>
                  删除模板
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>

        <!-- 生成合同按钮 -->
        <div class="mt-4" v-if="selectedTemplate">
          <a-button
            type="primary"
            size="large"
            @click="generateContract"
            :loading="generateContractLoading"
            class="w-full"
          >
            <template #icon><icon-file /></template>
            生成合同
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 查看已有合同模板弹窗 -->
    <a-modal
      v-model:visible="existingTemplatesVisible"
      title="已有合同模板"
      width="1000px"
      :footer="false"
    >
      <div v-if="existingTemplatesLoading" class="loading-container">
        <a-spin size="large" />
        <div class="mt-2 text-gray-500">加载中...</div>
      </div>

      <div
        v-else-if="existingTemplatesList.length === 0"
        class="empty-container"
      >
        <a-empty description="暂无合同模板" />
      </div>

      <div v-else class="contract-grid">
        <div
          v-for="template in existingTemplatesList"
          :key="template.tradeApplicationContractFileId"
          class="contract-item"
        >
          <a-card class="contract-card" hoverable>
            <div class="contract-header">
              <div class="contract-icon">
                <a-avatar :size="48" class="bg-green-100" shape="square">
                  <icon-file-pdf class="text-green-600" />
                </a-avatar>
              </div>
              <div class="contract-info">
                <div class="contract-title">
                  {{
                    template.contractTemplate?.fileName ||
                    template.file?.fileName ||
                    "合同模板"
                  }}
                </div>
                <div class="contract-meta">
                  <span class="contract-type">{{
                    dicts[proxy.DICT.lindiTradeApplicationContractType][
                      template.contractType
                    ]["dictValue"] || "标准模板"
                  }}</span>
                </div>
              </div>
            </div>

            <div class="contract-details">
              <div class="detail-row">
                <span class="detail-label">文件名称：</span>
                <span class="detail-value">{{
                  template.contractTemplate?.fileName ||
                  template.file?.fileName ||
                  "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">文件大小：</span>
                <span class="detail-value">{{
                  formatFileSize(
                    template.contractTemplate?.fileSize ||
                      template.file?.fileSize
                  )
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">文件类型：</span>
                <span class="detail-value">{{
                  (
                    template.contractTemplate?.fileType ||
                    template.file?.fileType
                  )?.toUpperCase() || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">创建时间：</span>
                <span class="detail-value">{{
                  formatDateTime(template.createTime)
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">更新时间：</span>
                <span class="detail-value">{{
                  formatDateTime(template.updateTime)
                }}</span>
              </div>
              <div
                v-if="
                  template.contractTemplate?.remark || template.file?.remark
                "
                class="detail-row"
              >
                <span class="detail-label">备注：</span>
                <span class="detail-value">{{
                  template.contractTemplate?.remark || template.file?.remark
                }}</span>
              </div>
            </div>

            <div class="contract-actions">
              <a-space>
                <a-button
                  size="mini"
                  @click="previewExistingTemplate(template)"
                >
                  <template #icon>
                    <icon-eye />
                  </template>
                  预览
                </a-button>
                <a-button
                  size="mini"
                  type="primary"
                  @click="downloadExistingTemplate(template)"
                >
                  <template #icon>
                    <icon-download />
                  </template>
                  下载
                </a-button>

                <a-button
                  size="mini"
                  status="danger"
                  @click="deleteExistingTemplate(template)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script setup>
import {
  getCurrentInstance,
  defineProps,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  nextTick,
} from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconRefresh,
  IconPlus,
  IconEye,
  IconEdit,
  IconDelete,
  IconDownload,
  IconFilePdf,
  IconInfoCircle,
  IconFile,
  IconFileImage,
  IconCalendar,
  IconFolder,
} from "@arco-design/web-vue/es/icon";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";
import {
  getTradeApplicationContractListByTradeApplicationIdApi,
  addTradeApplicationContractApi,
  updateTradeApplicationContractByTradeApplicationContractIdApi,
  deleteTradeApplicationContractByTradeApplicationContractIdApi,
  getContractTemplateListApi,
} from "~/api/lindi/tradeApplicationContract.js";
import {
  getPageTradeApplicationTemplateContractListApi,
  generateTemplateContractApi,
  deleteTradeApplicationTemplateContractByTradeApplicationTemplateContractIdApi,
} from "~/api/lindi/tradeApplicationTemplateContract.js";
import { deleteFileApi } from "~/api/basic/file.js";
import { LoadDicts, DICT } from "~/utils/dict.js";

// 定义props
const props = defineProps({
  tradeApplicationId: {
    type: String,
    required: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

//全局实例
const { proxy } = getCurrentInstance();

// 加载字典
const dicts = proxy.LoadDicts([
  DICT.lindiTradeApplicationContractType,
  DICT.commonNumberStatus,
  DICT.lindiContractTemplateType,
]);

// 组件卸载时清理数据
onUnmounted(() => {
  // 清理响应式数据，防止内存泄漏和上下文失效错误
  contractTemplates.value = [];
  selectedTemplate.value = null;
  selectedTemplateId.value = null;
  selectedContractType.value = "";
  contractList.value = [];
  existingTemplatesList.value = [];
});

// 响应式数据
// const loading = ref(false); // 使用父组件传递的loading状态
const modalVisible = ref(false);
const modalTitle = ref("上传合同");
const formRef = ref(null);
const contractUploadFileRef = ref(null);
const contractList = ref([]);
const editingContract = ref(null);
const existingFiles = ref([]);
const newUploadedFileIds = ref([]); // 跟踪新上传的文件ID，用于取消时清理
const submitLoading = ref(false); // 提交加载状态

// 模板信息弹窗相关
const templateDetailVisible = ref(false);
const templateListVisible = ref(false);
const selectedTemplateInfo = ref(null);
const contractTemplates = ref([]);
const contractTemplatesLoading = ref(false);
const selectedTemplate = ref(null);
const selectedTemplateId = ref(null);
const selectedContractType = ref("");
const generateContractLoading = ref(false);

// 已有合同模板列表相关
const existingTemplatesVisible = ref(false);
const existingTemplatesList = ref([]);
const existingTemplatesLoading = ref(false);

// 文件来源配置
const fs =
  fileSource.lindi_trade_contract_file?.key ||
  "lindi_trade_application_contract_file";

// 表单数据
const formData = reactive({
  tradeApplicationContractId: null,
  contractTemplateId: null,
  tradeApplicationId: null,
  contractFileId: null,
  contractName: "",
  contractNumber: "",
  contractAmount: "",
  effectiveDate: "",
  contractType: "",
  contractFile: null,
});

// 表单验证规则
const formRules = {
  contractName: [{ required: true, message: "请输入合同名称" }],
  contractNumber: [{ required: true, message: "请输入合同编号" }],
  contractType: [{ required: true, message: "请选择合同类型" }],
  effectiveDate: [{ required: true, message: "请选择签订日期" }],
};

// 获取合同类型文本
const getContractTypeText = (type) => {
  if (!type || !dicts[proxy.DICT.lindiTradeApplicationContractType]) {
    return "未知类型";
  }
  const dict = dicts[proxy.DICT.lindiTradeApplicationContractType].find(
    (d) => String(d.dictKey) === String(type)
  );
  return dict ? dict.dictValue : "未知类型";
};

// 加载合同列表
const loadContracts = () => {
  if (!props.tradeApplicationId) {
    return;
  }

  getTradeApplicationContractListByTradeApplicationIdApi(
    props.tradeApplicationId
  )
    .then((res) => {
      contractList.value = res || [];
      console.log("contractList.value", contractList.value);
    })
    .catch((error) => {
      console.error("获取合同信息失败:", error);
      Message.error("获取合同信息失败");
      contractList.value = [];
    });
};

// 刷新数据
const refreshData = () => {
  loadContracts();
};

// 显示新增弹窗
const showAddModal = () => {
  modalTitle.value = "上传合同";
  editingContract.value = null;
  newUploadedFileIds.value = []; // 清空文件跟踪
  resetForm();
  modalVisible.value = true;
};

// 显示合同模板列表
const showContractTemplates = () => {
  // 重置选择状态
  selectedTemplate.value = null;
  selectedTemplateId.value = null;
  selectedContractType.value = "";
  contractTemplates.value = [];

  // 先显示弹窗
  templateListVisible.value = true;

  // 再加载数据
  contractTemplatesLoading.value = true;

  getContractTemplateListApi()
    .then((res) => {
      // 确保数据是响应式的
      contractTemplates.value = Array.isArray(res) ? res : [];

      // 使用 nextTick 确保 DOM 更新后再设置默认值
      nextTick(() => {
        if (contractTemplates.value.length > 0) {
          // 设置第一个模板为默认选择
          const firstTemplate = contractTemplates.value[0];
          selectedTemplateId.value = firstTemplate.contractTemplateId;
          selectedTemplate.value = firstTemplate;

          // 自动设置合同类型
          if (firstTemplate?.contractTemplateType) {
            const autoContractType = getContractTypeByTemplate(
              firstTemplate.contractTemplateType
            );
            selectedContractType.value = autoContractType;
          }
        } else {
          Message.info("暂无合同模板");
        }
      });
    })
    .catch((error) => {
      console.error("获取合同模板失败:", error);
      Message.error("获取合同模板失败");
      contractTemplates.value = [];
    })
    .finally(() => {
      contractTemplatesLoading.value = false;
    });
};

// 显示已有合同模板列表
const showExistingTemplates = () => {
  // 先显示弹窗
  existingTemplatesVisible.value = true;

  // 再加载数据
  existingTemplatesLoading.value = true;

  // 构建查询参数
  const queryParams = {
    current: 1,
    size: 100, // 获取所有模板
    tradeApplicationId: props.tradeApplicationId,
  };

  getPageTradeApplicationTemplateContractListApi(queryParams)
    .then((res) => {
      existingTemplatesList.value = res.records || [];
    })
    .catch((error) => {
      console.error("获取已有合同模板失败:", error);
      Message.error("获取已有合同模板失败");
    })
    .finally(() => {
      existingTemplatesLoading.value = false;
    });
};

// 预览已有合同模板
const previewExistingTemplate = (template) => {
  const fileUrl = template.contractTemplate?.fileUrl || template.file?.fileUrl;
  if (fileUrl) {
    window.open(fileUrl, "_blank");
  } else {
    Message.warning("该模板暂无文件可预览");
  }
};

// 下载已有合同模板
const downloadExistingTemplate = (template) => {
  const fileUrl = template.contractTemplate?.fileUrl || template.file?.fileUrl;
  const fileName =
    template.contractTemplate?.fileName || template.file?.fileName;
  if (fileUrl) {
    const link = document.createElement("a");
    link.href = fileUrl;
    link.download = fileName || "合同模板.pdf";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("该模板暂无文件可下载");
  }
};

// 编辑已有合同模板
const editExistingTemplate = (template) => {
  Message.info("编辑模板功能开发中...");
  // TODO: 实现编辑模板功能
};

// 删除已有合同模板
const deleteExistingTemplate = (template) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除模板"${
      template.contractTemplate?.fileName || template.file?.fileName
    }"吗？`,
    onOk: () => {
      console.log("template", template);
      deleteTradeApplicationTemplateContractByTradeApplicationTemplateContractIdApi(
        template.tradeApplicationContractFileId
      )
        .then(() => {
          Message.success("删除成功");
          showExistingTemplates(); // 重新加载列表
        })
        .catch((error) => {
          console.error("删除模板失败:", error);
          Message.error("删除模板失败");
        });
    },
  });
};

// 预览合同
const previewContract = (contract) => {
  if (contract.contractFile?.fileUrl) {
    window.open(contract.contractFile.fileUrl, "_blank");
  } else {
    Message.warning("该合同暂无文件可预览");
  }
};

// 下载合同
const downloadContract = (contract) => {
  if (contract.contractFile?.fileUrl) {
    const link = document.createElement("a");
    link.href = contract.contractFile.fileUrl;
    link.download =
      contract.contractFile.fileName || `${contract.contractNumber}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("该合同暂无文件可下载");
  }
};

// 编辑合同
const editContract = (contract) => {
  modalTitle.value = "编辑合同";
  editingContract.value = contract;
  newUploadedFileIds.value = []; // 清空文件跟踪
  Object.assign(formData, {
    tradeApplicationContractId: contract.tradeApplicationContractId,
    contractTemplateId: contract.contractTemplateId,
    tradeApplicationId: contract.tradeApplicationId,
    contractFileId: contract.contractFileId,
    contractNumber: contract.contractNumber,
    contractName: contract.contractName,
    contractAmount: contract.contractAmount,
    effectiveDate: contract.effectiveDate,
    contractType: contract.contractType,
  });

  // 设置已有附件列表
  if (contract.contractFile) {
    existingFiles.value = [
      {
        fileId: contract.contractFile.fileId,
        fileName: contract.contractFile.fileName,
        fileUrl: contract.contractFile.fileUrl,
        fileType: contract.contractFile.fileType || "pdf",
        uploadTime: contract.contractFile.createTime || contract.createTime,
      },
    ];

    // 设置上传组件的文件列表用于回显
    if (contractUploadFileRef.value) {
      setTimeout(() => {
        if (
          contractUploadFileRef.value &&
          contractUploadFileRef.value.fileList !== undefined
        ) {
          contractUploadFileRef.value.fileList = [
            {
              uid: contract.contractFile.fileId,
              name: contract.contractFile.fileName,
              url: contract.contractFile.fileUrl,
              status: "done",
              response: { fileId: contract.contractFile.fileId },
            },
          ];
        }
      }, 0);
    }
  } else {
    existingFiles.value = [];
  }

  modalVisible.value = true;
};

// 删除合同
const deleteContract = (contract) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除合同「${contract.contractName}」吗？`,
    onOk: () => {
      deleteTradeApplicationContractByTradeApplicationContractIdApi(
        contract.tradeApplicationContractId
      )
        .then((res) => {
          if (res.code === 200) {
            Message.success("合同删除成功");
            loadContracts();
          } else {
            Message.error(res.message || "删除合同失败");
          }
        })
        .catch((error) => {
          console.error("删除合同失败:", error);
          Message.error("删除合同失败");
        });
    },
  });

  // 加载字典
};

// 文件上传处理
const handleFileChange = (fileList, fileItem) => {
  if (fileItem.status === "done") {
    formData.contractFile = fileItem;
  }
};

// 文件移除处理
const handleFileRemove = (fileItem) => {
  formData.contractFile = null;
  return true;
};

// 提交表单
const handleSubmit = () => {
  // 表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      return false;
    }

    // 开启加载状态
    submitLoading.value = true;

    // 准备提交数据
    const submitData = {
      ...formData,
      tradeApplicationId: props.tradeApplicationId,
    };

    // 处理签订日期格式，确保与后端 LocalDateTime 兼容
    if (submitData.effectiveDate) {
      if (typeof submitData.effectiveDate === "object") {
        // 如果是Date对象，转换为LocalDateTime格式
        const date = new Date(submitData.effectiveDate);
        if (!isNaN(date.getTime())) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          const hours = String(date.getHours()).padStart(2, "0");
          const minutes = String(date.getMinutes()).padStart(2, "0");
          const seconds = String(date.getSeconds()).padStart(2, "0");
          submitData.effectiveDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
      } else if (
        typeof submitData.effectiveDate === "string" &&
        submitData.effectiveDate.length === 10
      ) {
        // 如果是日期字符串格式（YYYY-MM-DD），添加时间部分
        submitData.effectiveDate = submitData.effectiveDate + " 00:00:00";
      }
    }

    // 处理文件上传
    if (
      contractUploadFileRef.value &&
      contractUploadFileRef.value.fileList &&
      contractUploadFileRef.value.fileList.length > 0
    ) {
      const file = contractUploadFileRef.value.fileList[0];
      console.log("file", file);
      if (file && file.response && file.response.fileId) {
        submitData.contractFileId = file.response.fileId;
      } else if (file && file.uid && existingFiles.value.length > 0) {
        // 使用已有文件
        submitData.contractFileId = existingFiles.value[0].fileId;
      }
    } else {
      // 如果没有新上传的文件，但有已有文件，使用已有文件的ID
      if (existingFiles.value.length > 0) {
        submitData.contractFileId = existingFiles.value[0].fileId;
      }
    }

    // 如果仍然没有获取到文件ID，尝试使用getUploadFileId方法
    if (!submitData.contractFileId && contractUploadFileRef.value) {
      const uploadFileIds = contractUploadFileRef.value.getUploadFileId();
      if (uploadFileIds) {
        // getUploadFileId返回逗号分隔的字符串，取第一个
        const fileIdArray = uploadFileIds.split(",").filter(Boolean);
        if (fileIdArray.length > 0) {
          submitData.contractFileId = fileIdArray[0];
        }
      }
    }

    console.log("submitData", submitData);

    // 执行提交操作
    const submitPromise = editingContract.value
      ? updateTradeApplicationContractByTradeApplicationContractIdApi({
          tradeApplicationContractId:
            editingContract.value.tradeApplicationContractId,
          ...submitData,
        })
      : addTradeApplicationContractApi(submitData);

    submitPromise
      .then((response) => {
        if (response.code === 200) {
          Message.success(
            editingContract.value ? "合同更新成功" : "合同添加成功"
          );
          // 成功保存后，清空新上传文件ID跟踪（因为文件已经被正式使用）
          newUploadedFileIds.value = [];
          modalVisible.value = false;
          resetForm();
          loadContracts();
        } else {
          Message.error(response.message || "操作失败，请重试");
        }
      })
      .catch((error) => {
        console.error("提交失败:", error);
        Message.error("操作失败，请重试");
      })
      .finally(() => {
        submitLoading.value = false;
      });
  });

  // 加载字典
};

// 预览文件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.warning("文件链接不存在");
  }
};

// 下载文件
const downloadFile = (file) => {
  if (file.fileUrl) {
    const link = document.createElement("a");
    link.href = file.fileUrl;
    link.download = file.fileName || "download";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("文件链接不存在");
  }
};

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  if (response && response.fileId) {
    // 只有在新增模式下才跟踪文件ID（编辑模式下不需要跟踪，因为是替换已有文件）
    if (!editingContract.value) {
      newUploadedFileIds.value.push(response.fileId);
    }
    console.log("文件上传成功，文件ID:", response.fileId);
  }
};

// 删除已有附件
const removeExistingFile = (index) => {
  existingFiles.value.splice(index, 1);
  // 同时清空上传组件的文件列表
  if (
    contractUploadFileRef.value &&
    contractUploadFileRef.value.fileList !== undefined
  ) {
    contractUploadFileRef.value.fileList = [];
  }
};

// 处理模态框取消/关闭事件
const handleModalCancel = async () => {
  // 清理新上传但未保存的文件
  await cleanupUnusedFiles();
  // 重置表单
  resetForm();
};

// 清理未使用的文件
const cleanupUnusedFiles = async () => {
  if (newUploadedFileIds.value.length > 0) {
    try {
      // 删除所有新上传但未保存的文件
      for (const fileId of newUploadedFileIds.value) {
        await deleteFileApi(fileId);
      }
      console.log("已清理未保存的文件:", newUploadedFileIds.value);
    } catch (error) {
      console.error("清理文件失败:", error);
    } finally {
      newUploadedFileIds.value = [];
    }
  }
};

// 重置表单
const resetForm = () => {
  editingContract.value = null;
  Object.assign(formData, {
    tradeApplicationContractId: null,
    contractTemplateId: null,
    tradeApplicationId: null,
    contractFileId: null,
    contractNumber: "",
    contractName: "",
    contractAmount: null,
    effectiveDate: "",
    contractType: "trade",
  });

  existingFiles.value = [];
  newUploadedFileIds.value = [];

  // 清空上传组件的文件列表
  if (
    contractUploadFileRef.value &&
    contractUploadFileRef.value.fileList !== undefined
  ) {
    contractUploadFileRef.value.fileList = [];
  }

  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 显示模板信息
const showTemplateInfo = (template) => {
  // 模拟模板详细信息，实际应该从API获取
  selectedTemplateInfo.value = {
    fileId: template.templateId || "template_001",
    fileName: template.templateName || "标准林地指标交易合同模板.pdf",
    fileSize: 2048576, // 2MB
    fileType: "pdf",
    fileUrl: template.templateUrl || "/files/templates/standard_contract.pdf",
    status: "active",
    createTime: "2024-01-15 10:30:00",
    updateTime: "2024-01-20 14:20:00",
    remark: "适用于标准林地指标交易的合同模板，包含完整的交易条款和法律条文。",
  };
  templateDetailVisible.value = true;
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });

  // 加载字典
};

// 根据模板类型确定合同类型
const getContractTypeByTemplate = (templateType) => {
  // 调试：打印字典数据

  // 获取字典中的第一个选项作为默认值
  const dictItems = dicts[proxy.DICT.lindiTradeApplicationContractType];
  if (dictItems && dictItems.length > 0) {
    console.log("使用字典第一个选项:", dictItems[0]);
    return dictItems[0].dictKey;
  }

  // 原有的映射逻辑作为备用
  const typeMap = {
    交易合同: "trade",
    补充协议: "supplement",
    修改协议: "amendment",
    终止协议: "termination",
  };
  return typeMap[templateType] || "trade";
};

// 模板选择变化
const onTemplateChange = (templateId) => {
  console.log("模板ID选择变化:", templateId);

  // 防止无效的 templateId
  if (!templateId) {
    selectedTemplate.value = null;
    selectedContractType.value = "";
    return;
  }

  // 根据templateId找到对应的模板对象
  const template = contractTemplates.value.find(
    (t) => t.contractTemplateId === templateId
  );

  if (template) {
    selectedTemplate.value = template;
    console.log("找到的模板对象:", template);

    // 根据模板类型自动设置合同类型（可选）
    if (template.contractTemplateType) {
      const autoContractType = getContractTypeByTemplate(
        template.contractTemplateType
      );
      console.log("自动设置合同类型:", autoContractType);
      selectedContractType.value = autoContractType;
    }
  } else {
    console.warn("未找到对应的模板对象:", templateId);
    selectedTemplate.value = null;
    selectedContractType.value = "";
  }

  console.log(
    "模板选择后，selectedContractType值:",
    selectedContractType.value
  );
};

// 预览模板
const previewTemplate = (template) => {
  if (template.contractTemplateFile?.fileUrl) {
    window.open(template.contractTemplateFile.fileUrl, "_blank");
  } else {
    Message.warning("该模板暂无文件可预览");
  }
};

// 下载模板
const downloadTemplate = (template) => {
  if (template.contractTemplateFile?.fileUrl) {
    const link = document.createElement("a");
    link.href = template.contractTemplateFile.fileUrl;
    link.download =
      template.contractTemplateFile.fileName ||
      `${template.contractTemplateName}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("该模板暂无文件可下载");
  }
};

// 删除模板
const deleteTemplate = (template) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除模板「${template.contractTemplateName}」吗？此操作不可恢复。`,
    onOk: () => {
      // 这里应该调用删除模板的API
      // deleteContractTemplateApi(template.contractTemplateId)
      //   .then(() => {
      //     Message.success('删除成功');
      //     showContractTemplates(); // 重新加载模板列表
      //   })
      //   .catch((error) => {
      //     console.error('删除模板失败:', error);
      //     Message.error('删除模板失败');
      //   });

      Message.info("删除模板功能待实现");
    },
  });

  // 加载字典
};

// 生成合同
const generateContract = () => {
  if (!selectedTemplate.value?.contractTemplateId) {
    Message.warning("请先选择合同模板");
    return;
  }

  if (!selectedContractType.value) {
    Message.warning("请选择合同类型");
    return;
  }

  generateContractLoading.value = true;

  // 准备生成合同的数据，包含contractType字段
  const generateData = {
    tradeApplicationId: props.tradeApplicationId,
    contractTemplateId: selectedTemplate.value.contractTemplateId,
    contractType: selectedContractType.value,
  };

  generateTemplateContractApi(generateData)
    .then((res) => {
      Message.success("合同生成成功");
      templateListVisible.value = false;
      // 重置选择
      selectedTemplate.value = null;
      selectedContractType.value = "";
      loadContracts(); // 重新加载合同列表
    })
    .catch((error) => {
      console.error("生成合同失败:", error);
      Message.error("生成合同失败");
    })
    .finally(() => {
      generateContractLoading.value = false;
    });

  // 加载字典
};

// 组件挂载时加载数据
onMounted(() => {
  loadContracts();
});
</script>

<style scoped>
.contract-management {
  padding: 16px;
}

.upload-section {
  margin-bottom: 24px;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  background: #fafafa;
  transition: all 0.3s;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.upload-area.dragover {
  border-color: #1890ff;
  background: #e6f7ff;
}

.upload-icon {
  font-size: 48px;
  color: #d9d9d9;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 14px;
  color: #999;
}

.contract-list {
  margin-top: 24px;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.contract-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.contract-item {
  width: 100%;
}

.contract-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.contract-card :deep(.arco-card-body) {
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.contract-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.contract-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.contract-info {
  flex: 1;
  min-width: 0;
}

.contract-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  word-break: break-all;
  line-height: 1.4;
}

.contract-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.contract-type {
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.contract-details {
  flex: 1;
  margin-bottom: 16px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 13px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #666;
  flex-shrink: 0;
  margin-right: 8px;
  font-weight: 500;
}

.detail-value {
  color: #333;
  text-align: right;
  word-break: break-all;
  flex: 1;
}

.detail-value.amount {
  color: #f53f3f;
  font-weight: 600;
}

.contract-actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  margin-top: auto;
}

.contract-actions :deep(.arco-space) {
  width: 100%;
  justify-content: center;
}

.bg-blue-100 {
  background-color: #e6f7ff;
}

.text-blue-600 {
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .contract-grid {
    grid-template-columns: 1fr;
  }

  .contract-management {
    padding: 12px;
  }

  .upload-area {
    padding: 30px 20px;
  }

  .upload-icon {
    font-size: 36px;
  }

  .upload-text {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .contract-grid {
    gap: 12px;
  }

  .contract-card :deep(.arco-card-body) {
    padding: 12px;
  }

  .contract-title {
    font-size: 14px;
  }

  .detail-row {
    font-size: 12px;
  }
}
</style>
